/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-08-18
 * Time: 15:51
 */
public class MyBlockingQueue {
    private String[] data;  //存储数据
    private int head = 0;//队头
    private int tail = 0;   //队尾
    private int size = 0;   //有效元素个数
    private Object locker = new Object();
    public MyBlockingQueue(int capacity){
        if (capacity <= 0) {
            throw new IllegalArgumentException("capacity must be positive.");
        }
        data = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker){
            while(size == data.length){
                locker.wait(); //队列满了, 那么进入等待状态, 等待数据入队列
            }
            data[tail] = elem;
            tail++;
            if(tail >= data.length){    //循环队列满了
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (locker){
            while(size == 0){
                locker.wait(); //队列空了, 没有数据可以出队列了, 进入等待状态
            }
            String ret = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }

}
